package com.mid;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by Lxk on 2019/5/31.
 */
public class Solution449 {

    void getSerialize(TreeNode node, StringBuffer sb) {
        if (node == null) {
            sb.append("#!");
            return;
        }
        sb.append(node.val + "!");
        getSerialize(node.left, sb);
        getSerialize(node.right, sb);
    }

    public String serialize(TreeNode root) {
        StringBuffer sb = new StringBuffer();
        getSerialize(root, sb);
        return sb.toString();
    }

    TreeNode getDeserialize(Queue<String> queue) {
        String cur = queue.poll();
        if ("#".equals(cur)) {
            return null;
        }
        TreeNode node = new TreeNode(Integer.valueOf(cur));
        node.left = getDeserialize(queue);
        node.right = getDeserialize(queue);
        return node;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] arr = data.split("!");
        Queue<String> queue = new LinkedList<>();
        for (String val : arr) {
            queue.add(val);
        }
        TreeNode node = getDeserialize(queue);
        return node;
    }


}
